/*
 * High Level API for Nokia LCD
 */

#include "display/lcd.h"
#include "math/geometry.h"
#include "display/fonts.h"

/**
 * Notes about Screen boundaries and coordinate system
 *
 * Screen coorners are (0,2) (0,131) (129,2) (129,131);
 * where (0,2) is button rigth corner
 * and (129,131) is upper left corner *
 * */

/************************** High Level API *******************************/

void lcd_Init() {
	spilcd_Init();
}

void inline lcd_ClearScreen(unsigned int color) {
	spilcd_ClearScreen(color);
}

/**
 * Point primitive
 */
void inline lcd_DrawPoint(Point * point, unsigned int color) {
	spilcd_PutPixel(color, point->x, point->y);
}

void lcd_WriteChar(char c, unsigned short x, unsigned short y, int size,
		unsigned short fColor, unsigned short bColor) {
	unsigned char aux1, aux2;
	extern const char LCD_FONT6x8[97][8];
	extern const char LCD_FONT8x8F[97][8];
	extern const char LCD_FONT8x16[97][16];

	int i, j;

	unsigned int nCols;
	unsigned int nRows;
	unsigned int nBytes;
	unsigned char PixelRow;

	unsigned char Mask;

	unsigned short color;
	unsigned char *pFont;
	unsigned char *pChar;

	unsigned char *FontTable[] = { (unsigned char *) LCD_FONT6x8,
			(unsigned char *) LCD_FONT8x8F, (unsigned char *) LCD_FONT8x16 };

	// get pointer to the beginning of the selected font table
	pFont = (unsigned char *) FontTable[size];
	// get the nColumns, nRows and nBytes
	nCols = *pFont;
	nRows = *(pFont + 1);
	nBytes = *(pFont + 2);
	// get pointer to the last byte of the desired character
	pChar = pFont + (nBytes * (c - 0x1F)) + nBytes - 1;

	for (i = nRows - 1; i >= 0; i--) {
		//lcdMoveTo(x, y + i);
		/*
		 * 		spilcd_GotoXY(x,y + i);
		 spilcd_SendCommand(RAMWR_NXP);
		 */
		// copy pixel row from font table and then decrement row
		PixelRow = *pChar--;

		Mask = 0x80;

		for (j = 0; j < nCols; j += 1) {
			if ((PixelRow & Mask) == 0)
				color = bColor;
			else
				color = fColor;
			Mask = Mask >> 1;

			/*
			 cDisp_CS_LO();
			 cDispWrDat((INT8U) (color >> 8), (INT8U) color);
			 cDisp_CS_HI();
			 */
			/*aux1 = ((color >> 4) & 0xFFFF);
			 aux2 = (((color & 0x0F) << 4) | 0x00);

			 SPI_LCD_senddata((unsigned char)aux1);
			 SPI_LCD_senddata((unsigned char)aux2);
			 spilcd_SendCommand(NOP_NXP);*/
			spilcd_PutPixel(color, x + j, y + i);
		}
	}
}

void lcd_WriteString(char *pString, int x, int y, int Size, int fColor,
		int bColor) {
	// loop until null-terminator is seen
	while (*pString != 0x00) {
		// draw the character

		lcd_WriteChar(*pString++, x, y, Size, fColor, bColor);
		// advance the y position
		if (Size == 0)
			x = x + 6;
		else if (Size == 1)
			x = x + 8;
		else
			x = x + 8;
		// bail out if y exceeds 131
		if (x > LCD_SCR_WIDTH)
			break;
	}
}
